package com.ijiuchuang.jc_localization.tools.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.ijiuchuang.jc_localization.R;

/**
 * 工具类
 * Created by 王伟 on 2016/3/20.
 */
public class MyUtil {

    /**
     * 获取设备ID
     * @param context 当前Activity上下文
     * @return 设备id
     */
    public static String getDeviceId(Context context) {
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 获取版本号
     * @param context 当前Activity上下文
     * @return 版本号
     */
    public static String getVersion(Context context)
    {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi=pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return context.getString(R.string.app_version_unknown);
        }
    }

    /**
     * 获取版本号(内部识别号)
     * @param context 当前Activity上下文
     * @return 版本号
     */
    public static int getVersionCode(Context context)
    {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi=pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 重新计算 listview 大小
     * @param listView 子listview
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
